package com.milk.milkmedia.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.dao.Dao;
import com.milk.milkmedia.R;
import com.milk.milkmedia.api.BaseActivity;
import com.milk.milkmedia.api.ConstantField;
import com.milk.milkmedia.dao.DBManager;
import com.milk.milkmedia.dao.MusicInfoDB;
import com.milk.milkmedia.service.MusicPlayService;
import com.milk.milkmedia.utils.LrcHandle;
import com.milk.milkmedia.utils.LyricAdapter;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by 微安 on 2015/8/9.
 */
public class MusicPlayAcitivity extends BaseActivity implements View.OnClickListener {

    private ImageView mPlayButton = null;
    private ImageView mNextPlayButton = null;
    private ImageView mPrePlayButton = null;
    private ImageView iModeButton = null;
    public static SeekBar iMusicSeekBar = null;
    private SeekBar mAudioSeekBar = null;
    private AudioManager mAudioManager = null;
    private boolean mIsChange = false;
    private boolean mIsPlay = false;
    private int mPosition;
    private int iMaxVolume;
    private int totlCount;
    private Intent musicServiceIntent;
    private ListView mLyricView;
    private List<Map<String, Object>> mLyrics;
    private Context mContext;
    private Handler mHandler;
    private LyricAdapter mLyricAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_musicplay);
        restoreActionBar();
        Intent intent = getIntent();
        mContext = this;
        mPosition = intent.getIntExtra("position", 0);
        musicServiceIntent = new Intent(this, MusicPlayService.class);
        initView();
        initBroadCast();
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.lightblue));
        actionBar.setDisplayShowTitleEnabled(true);
    }
    private void initBroadCast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantField.ACTION_UPDATE);
        MusicPlayerReceiver broadcastReceiver = new MusicPlayerReceiver();
        registerReceiver(broadcastReceiver, filter);
    }

    class MusicPlayerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mPosition = intent.getIntExtra("position", 0);
            Log.e(HomePageActivity.Tag, "广播收到的" + mPosition);
            showLyric();
        }
    }



    private void initView() {
        Intent intent = new Intent(this,MusicPlayService.class);
        startService(intent);
        mPlayButton = (ImageView) findViewById(R.id.mplay_play);
        mPlayButton.setOnClickListener(this);
        mNextPlayButton = (ImageView) findViewById(R.id.mplay_next);
        mNextPlayButton.setOnClickListener(this);
        mPrePlayButton = (ImageView) findViewById(R.id.mplay_pre);
        mPrePlayButton.setOnClickListener(this);
        iModeButton = (ImageView) findViewById(R.id.mplay_mode);
        iModeButton.setOnClickListener(this);
        mAudioSeekBar = (SeekBar) findViewById(R.id.mplay_audio_sb);
        mAudioSeekBar.setOnSeekBarChangeListener(new AudioSeekBarChangeEvent());
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        iMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.e(HomePageActivity.Tag, "" + iMaxVolume);
        mAudioSeekBar.setMax(iMaxVolume);
        mAudioSeekBar.setProgress(current);
        iMusicSeekBar = (SeekBar) findViewById(R.id.mpaly_music_sb);
        iMusicSeekBar.setOnSeekBarChangeListener(new MusicSeekBarChangeEvent());
        iMusicSeekBar.setOnClickListener(this);
        mLyricView = (ListView) findViewById(R.id.mplay_lyric_lv);
    }

    @Override
    public void onClick(View v) {
//        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.mplay_play:
                if (mIsPlay == false) {
                    mPlayButton.setImageResource(R.drawable.ic_mplay_play);
                    startAction(ConstantField.ACTION_PLAY);
                    showLyric();
                } else if (mIsPlay == true) {
                    mPlayButton.setImageResource(R.drawable.ic_mplay_stop);
                    startAction(ConstantField.ACTION_STOP);
                    mIsPlay = false;
                }
                break;
            case R.id.mplay_next:
                mPosition = mPosition + 1;
                if (mPosition >= totlCount) {
                    mPosition = 0;
                }
                startAction(ConstantField.ACTION_NEXT);
                showLyric();
                break;
            case R.id.mplay_pre:
                mPosition = mPosition - 1;
                if (mPosition < 0) {
                    mPosition = totlCount - 1;
                }
                startAction(ConstantField.ACTION_PREV);
                showLyric();
                break;
            case R.id.mplay_mode:
                Log.e(HomePageActivity.Tag, "模式是：" + ConstantField.MODE);
                switch (ConstantField.MODE) {
                    case ConstantField.PLAY_SINGLE_LOOP:
                        ConstantField.MODE = ConstantField.PLAY_RANDOM;
                        iModeButton.setImageResource(R.drawable.ic_mplay_random);
                        break;
                    case ConstantField.PLAY_RANDOM:
                        Log.e(HomePageActivity.Tag, "模式是：" + ConstantField.MODE);
                        iModeButton.setImageResource(R.drawable.ic_mplay_repeat);
                        ConstantField.MODE = ConstantField.PLAY_REPEAT;
                        break;
                    case ConstantField.PLAY_REPEAT:
                        Log.e(HomePageActivity.Tag, "模式是：" + ConstantField.MODE);
                        iModeButton.setImageResource(R.drawable.ic_mplay_list);
                        ConstantField.MODE = ConstantField.PLAY_LIST;
                        break;
                    case ConstantField.PLAY_LIST:
                        Log.e(HomePageActivity.Tag, "模式是：" + ConstantField.MODE);
                        iModeButton.setImageResource(R.drawable.ic_mplay_loop);
                        ConstantField.MODE = ConstantField.PLAY_SINGLE_LOOP;
                        break;
                }
                break;
            case R.id.mpaly_music_sb:
                int start = 0, end = 0;
                Log.e(HomePageActivity.Tag, "点击事件也是可以记录下iMusicSeekBar的进度");
                if (ConstantField.MODE == ConstantField.PLAY_REPEAT) {
                    start = iMusicSeekBar.getProgress();
                    Log.e(HomePageActivity.Tag, "点击事件也是可以记录下iMusicSeekBar的进度");
                }
                break;
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(this, ConstantField.TIMER_COUNT);
            int time = MusicPlayService.iMediaPlay.getCurrentPosition();
            int lyrictime, i;
            if (mLyrics != null && mLyrics.size() != 0) {
                for (i = 0; i < mLyrics.size(); i++) {
                    lyrictime = (int) mLyrics.get(i).get("time");
                    if (lyrictime >= time) {
                        break;
                    }
                }
                mLyricAdapter.sentCurrentTimePlayer(time);
                mLyricAdapter.notifyDataSetChanged();
                mLyricView.smoothScrollToPosition(i);
            }
        }
    };

    public List<Map<String, Object>> getLyricData() {
        String lyricPath = queryLyricUrl(mPosition);
        Log.e(HomePageActivity.Tag, "查询地址" + mPosition + lyricPath);
        if (lyricPath.equals("null") == false) {
            LrcHandle lrcHandler = new LrcHandle();
            if (lrcHandler.readLRC(lyricPath) == true) {

                List<Map<String, Object>> lyrics = lrcHandler.getmLyrics();
                return lyrics;
            }
        }
        return null;
    }

    class MusicSeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mIsChange = true;
            int cur = iMusicSeekBar.getProgress();
            iMusicSeekBar.setProgress(cur);
            if (MusicPlayService.iMediaPlay != null) {
                int start = 0, end = 0;
//                首先做存下start和end值传入给service播放
                if (ConstantField.MODE == ConstantField.PLAY_REPEAT) {
                    start = iMusicSeekBar.getProgress();
                    Log.e(HomePageActivity.Tag, "点击事件也是可以记录下iMusicSeekBar的进度");
                }
                MusicPlayService.iMediaPlay.seekTo(cur);
            } else {
                Log.e(HomePageActivity.Tag, "MusicPlayer未初始化就开始");
            }
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mIsChange = false;
            int cur = iMusicSeekBar.getProgress();
            iMusicSeekBar.setProgress(cur);
            if (MusicPlayService.iMediaPlay != null) {
                MusicPlayService.iMediaPlay.seekTo(cur);
            } else {
                Log.e(HomePageActivity.Tag, "MusicPlayer未初始化就结束");
            }
        }
    }

    class AudioSeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int curVolume = mAudioSeekBar.getProgress();
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume,
                    AudioManager.FLAG_PLAY_SOUND);
            Toast.makeText(getApplicationContext(), mAudioSeekBar.getProgress() + "",
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 根据Activity传来不同的动作启动服务
     *
     * @param action
     */
    public void startAction(String action) {
        Intent intent = new Intent();
        intent.setAction(ConstantField.ACTION);
        intent.putExtra("position", mPosition);
        intent.putExtra("action", action);
        sendBroadcast(intent);
        Log.e(HomePageActivity.Tag,"发送动作的广播");
//        startService(musicServiceIntent);
    }

    private String queryLyricUrl(int position) {
        try {
            Dao<MusicInfoDB, String> musicInfoDB = DBManager.getInstance().getMusicInfoBDHelper().getDao(MusicInfoDB.class);
            totlCount = musicInfoDB.queryForAll().size();
            List<MusicInfoDB> musicInfoDBs = musicInfoDB.queryBuilder().where().eq("id", position).query();
            if (musicInfoDBs.size() != 0) {
                return musicInfoDBs.get(0).getLyric_url();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(HomePageActivity.Tag, "查询Lyric地址错误");
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                mAudioSeekBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                mAudioManager.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                mAudioSeekBar.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showLyric() {
        TextView textView = (TextView) findViewById(R.id.mplay_alert_tv);
        Log.e(HomePageActivity.Tag, "调用showLyric");
        mLyrics = getLyricData();
        if (mLyrics != null && mLyrics.size() != 0) {
            mLyricView.setVisibility(View.VISIBLE);
            textView.setVisibility(View.INVISIBLE);
            mLyricAdapter = new LyricAdapter(mContext, mLyrics);
            mLyricView.setAdapter(mLyricAdapter);
            mIsPlay = true;
            mHandler = new Handler();
            mHandler.postDelayed(runnable, ConstantField.TIMER_COUNT);
        } else {
            mLyricView.setVisibility(View.INVISIBLE);
            textView.setVisibility(View.VISIBLE);
            textView.setText("无歌词赶紧下载");
        }
    }

}
